package com.chixing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chixing.entity.Users;
import com.chixing.entity.VO.LoginUser;
import com.chixing.mapper.UsersMapper;
import com.chixing.service.IUsersService;
import com.chixing.utils.JWTUtils;
import com.chixing.utils.Result;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author smith
 * @since 2025-09-30
 */
@Service
public class UsersServiceImpl implements IUsersService {

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private RedisTemplate<String , String> redisTemplate;

    String userRedisKey = "session_user_";

    @Override
    public Result login(String userName, String userPwd) {

        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", userName);

        Users user = usersMapper.selectOne(queryWrapper);

        if (user == null) {
            return Result.loginFail("用户不存在");
        }

        // 2. 校验密码
        boolean matches = BCrypt.checkpw(userPwd, user.getPassword()); // user.getPassword() 是数据库存的哈希
        if (!matches) {
            return Result.loginFail("密码错误");
        }else {
            //将用户信息封装成token
            String token = JWTUtils.createToken(user);
            //将token添加到redis中
            redisTemplate.opsForValue().set(userRedisKey+user.getUserId(),token,30, TimeUnit.MINUTES);

            return Result.loginSuccess(token);
        }
    }

    @Override
    public Result getLoginUserInfoById(String token) {
        int isValidToken =   JWTUtils.checkToken(token);
        if(isValidToken==0) {  // 有效的token
            LoginUser loginUser = JWTUtils.parseToken(token);
            if(loginUser !=null)
                return Result.getSuccess(loginUser);  // 200
            else
                return Result.getFail(null);//
        }else if(isValidToken ==1)
            return Result.loginTimeout(null); // 202
        else
            return Result.getFail(null);  // 201
    }

    @Override
    public Result logout(Integer userId) {
        Boolean isDelete = redisTemplate.delete(userRedisKey + userId);
        if (isDelete)
            return Result.logoutSuccess(isDelete);
        return Result.logoutFail(isDelete);
    }

    //续签
    @Override
    public Result validateAndRefreshToken(String token) {
        try {
            LoginUser loginUser = JWTUtils.parseToken(token);
            String storedTokenFromRedis = redisTemplate.opsForValue().get(userRedisKey + loginUser.getUserId());
            if (storedTokenFromRedis == null)
                return Result.getFail(false);
            if (!storedTokenFromRedis.equals(token))
                return Result.getFail(false);
            //刷新token
            redisTemplate.expire(userRedisKey+loginUser.getUserId(),30,TimeUnit.MINUTES);
            return Result.getSuccess(true);
        }catch (Exception e){
            return Result.getFail(false);
        }
    }

    @Override
    public Result regist(Users users) {
        String rawPassword = users.getPassword();

        // 加密
        String hashed = BCrypt.hashpw(rawPassword, BCrypt.gensalt());


        System.out.println("加密后：" + hashed);

        // 校验密码
        boolean matches = BCrypt.checkpw(rawPassword, hashed);
        System.out.println("是否匹配：" + matches);

        users.setPassword(hashed);

        users.setCreatedAt(LocalDateTime.now());
        int rows =  usersMapper.insert(users);
        if(rows >0)
            return Result.registSuccess(users);
        else
            return Result.registFail(users);
    }
}
